﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;

using CloudSoft.Extensions;

namespace ERPStore.Web.Exporter.EventConsumers
{
	public class NetAffTrackerOrderCreatedEventConsumer : EventBrokR.IConsumer<ERPStore.Web.Events.OrderCreatedEvent>
	{
		public NetAffTrackerOrderCreatedEventConsumer(ERPStore.Logging.ILogger logger
			, ERPStore.Services.IVisitorService visitorService)
		{
			Logger = logger;
			VisitorService = visitorService;
		}

		protected ERPStore.Logging.ILogger Logger { get; private set; }
		protected ERPStore.Services.IVisitorService VisitorService { get; private set; }

		public void Handle(ERPStore.Web.Events.OrderCreatedEvent @event)
		{
			var tracker = ERPStore.Configuration.ConfigurationSettings.AppSettings["netAffiliationTracker"];
			if (tracker.IsNullOrTrimmedEmpty())
			{
				return;
			}

			string trackUrl = null;
			bool sendNotification = false;
			if (@event.Order.Document != ERPStore.Models.SaleDocumentType.Quote)
			{
				var visitorHistory = VisitorService.GetVisitorHistory(@event.Cart.VisitorId);
				if (visitorHistory != null)
				{
					// TODO: Verifier que lors du track , un ajout au panier a bien eu lieu
					// ou que c'est le dernier track qui a permis la vente (retargeting)
					foreach (var track in visitorHistory.TrackList)
					{
						if (track.SourceId != null
							&& track.SourceId.Equals("F814535B-08A1-4CF6-BB2E-0C6177F6D16D", StringComparison.InvariantCultureIgnoreCase))
						{
							sendNotification = true;
							break;
						}
					}
				}

				trackUrl = string.Format("http://action.metaffiliation.com/suivi.php?mclic={0}&argtemp={1}&argann={2}", tracker, @event.Cart.Code, @event.Order.Code);
			}
			var httpClient = new HttpClient();
			try
			{
				if (sendNotification)
				{
					Logger.Notification("Send netaffilation notification for order {0}", @event.Order.Code);
					httpClient.GetAsync(trackUrl).Wait(5 * 1000);
				}
			}
			catch(Exception ex)
			{
				Logger.Error(ex);
			}
		}
	}
}
